<template>
  <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
    <div class="header-container user-container" ref="headerContainer">
      <!-- 操作 -->
      <a-row :gutter="8" class="opeattion-container">
        <a-col :span="16">
          <a-input-search
            name="filterText"
            @search="getSearchData"
            :placeholder="l('SearchWithThreeDot')"
            enterButton
            v-model:value="filterText"
          />
        </a-col>
        <a-col :span="6" :offset="2" style="text-align: right">
          <a
            @click="addRole()"
            v-if="isGranted('Pages.Administration.OrganizationUnits.ManageRoles')"
          >
            <plus-outlined /> {{ l('CreateNewRole') }}
          </a>
          <a-divider
            v-if="isGranted('Pages.Administration.OrganizationUnits.ManageRoles')"
            type="vertical"
          ></a-divider>
          <a
            @click="batchDelete()"
            v-if="isGranted('Pages.Administration.OrganizationUnits.ManageRoles')"
          >
            <delete-outlined />{{ l('BatchDelete') }}
          </a>
          <a-divider
            type="vertical"
            v-if="isGranted('Pages.Administration.OrganizationUnits.ManageRoles')"
          ></a-divider>
          <a :title="l('Refresh')" @click="refresh()"> <reload-outlined /></a>
        </a-col>
      </a-row>
      <!-- 数据部分 -->
      <div class="my-md">
        <a-alert :type="'info'" :showIcon="true">
          <template #message>
            <span v-html="l('GridSelectedXItemsTips', selectedRowKeys.length)"></span>
            <a @click="restCheckStatus()" class="ml-md">{{ l('ClearEmpty') }}</a>
            <a-divider type="vertical"></a-divider>
            <a @click="refresh()">{{ l('Refresh') }}</a>
          </template>
        </a-alert>
      </div>
      <a-table
        size="middle"
        :scroll="{ x: tableWidthScroll, y: 'calc(100vh - 555px)' }"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data-source="dataList"
        :pagination="{
          total: totalItems,
          current: pageNumber,
          pageSize: pageSize,
          showTotal: showTotalInfo,
          showQuickJumper: true,
          showSizeChanger: true,
          change: pageNumberChange,
          showSizeChange: pageNumberChange,
          pageSizeOptions: pageSizeOptions,
          size: 'middle',
        }"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          checkAll: checkAll,
        }"
        @change="tableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'addedTime'">
            {{ _moment(record.addedTime) }}
          </template>
          <template v-if="column.key === 'actions'">
            <span v-if="isGranted('Pages.Administration.OrganizationUnits.ManageUsers')">
              <a-popconfirm
                placement="top"
                :okText="l('Ok')"
                :cancelText="l('Cancel')"
                @confirm="removeMember(record)"
              >
                <template #title>
                  {{ l('ConfirmDeleteWarningMessage', record.userName, selectTree.displayName) }}
                </template>
                <a class="table-delete"> <delete-outlined />{{ l('Delete') }}</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { PagedListingComponentBase } from '/@/shared/component-base';
  import {
    OrganizationUnitListDto,
    OrganizationUnitServiceProxy,
    UserListDto,
  } from '/@/shared/service-proxies';
  import AddRoleComponent from '../add-role/add-role.vue';
  import { PlusOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons-vue';
  import _ from 'lodash';
  import { defineComponent } from 'vue';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
  import { ColumnType } from 'ant-design-vue/lib/table';

  export default defineComponent({
    components: {
      PlusOutlined,
      DeleteOutlined,
      ReloadOutlined,
    },
    name: 'organization-unit-role-panel',
    mixins: [PagedListingComponentBase],
    props: {
      selectTree: OrganizationUnitListDto,
    },
    data() {
      return {
        organizationUnitServiceProxy: new OrganizationUnitServiceProxy(),
        filteredInfo: null,
        sortedInfo: null,
        // 用户数据
        dataList: [] as UserListDto[],
      };
    },
    watch: {
      'selectTree.id': {
        handler() {
          this.refresh();
        },
      },
    },
    methods: {
      // 获取列
      getColumns(): ColumnType<UserListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('RoleName'),
            dataIndex: 'displayName',
            ellipsis: true,
            key: 'displayName',
          },
          {
            title: this.l('CreationTime'),
            dataIndex: 'addedTime',
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
            key: 'addedTime',
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            fixed: 'right',
            align: 'center',
            width: 250,
          },
        ];
      },
      /**
       * 拉取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        if (!this.selectTree?.id) return;
        this.organizationUnitServiceProxy
          .getPagedOrganizationUnitRoles(
            this.selectTree?.id,
            this.filterText,
            '',
            request.maxResultCount,
            request.skipCount,
          )
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      /**
       * 移除用户
       * @param user 当前用户实体
       */
      removeMember(user) {
        const _ouId = parseInt(this.selectTree.id);
        this.organizationUnitServiceProxy.removeRole(user.id, +_ouId).then(() => {
          this.notify.success(this.l('SavedSuccessfully'));

          abp.event.trigger('reloadOrganizationUnitTree', true);
          this.refresh();
        });
      },
      /**
       * 批量删除
       */
      batchDelete() {
        const selectCount = this.selectedRowKeys.length;
        if (selectCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', selectCount),
          '',
          (res) => {
            if (res) {
              const _ouId = parseInt(this.selectTree.id);
              const ids = _.map(this.selectedRowKeys);
              this.organizationUnitServiceProxy
                .batchRemoveRoleFromOrganizationUnit(_ouId, ids)
                .then(() => {
                  this.notify.success(this.l('SuccessfullyDeleted'));
                  this.refresh();
                  abp.event.trigger('reloadOrganizationUnitTree', true);
                });
            }
          },
        );
      },
      /**
       * 增加角色
       */
      addRole() {
        this.modalHelper
          .create(AddRoleComponent, {
            organizationUnitId: parseInt(this.selectTree.id),
          })
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
    },
  });
</script>

<style scoped lang="less">
  .dynamic-table {
    padding: 0;

    :deep(.toolbar-area) {
      margin-bottom: 10px;
    }
  }
</style>
